Ext.ns("Ext.master.functions");

/**
 * 节点管理
 * @class Master.functions.modulelist
 * @extends Ext.Panel
 */
Ext.master.functions.Management = Ext.extend(Ext.Panel, {
    layout: 'border',
    region: 'center',
    closable: true,
    initComponent: function() {
    	var funcListGridPanel = new Ext.master.functions.FunctionListGridPanel();
    	var moduleDescript = new Ext.master.functions.ModuleDescript();

    	var functionPanel = new Ext.master.functions.FunctionPanel({
    		moduleDescript : moduleDescript,
    		funcListPanel : funcListGridPanel
    	});
		var moduleTreePanel = new Ext.master.functions.ModuleTreePanel({
			functionPanel: functionPanel,
			funcListPanel : funcListGridPanel
		});
		
        this.items = [moduleTreePanel, functionPanel];
        Ext.master.functions.Management.superclass.initComponent.call(this);
    }
});

/**
 * 模块列表树
 * @class Ext.master.functions.ModuleTreePanel
 * @extends Ext.tree.TreePanel
 */
Ext.master.functions.ModuleTreePanel = Ext.extend(Ext.tree.TreePanel, {
	funcListPanel: null,
	functionPanel: null,
	
	constructor: function(_config) {
    	if (_config == null) {
			_config = {};
		}
		
		Ext.apply(this, _config);
		    
		Ext.master.functions.ModuleTreePanel.superclass.constructor.call(this, {
			id: 'moduleTree',
	        region: 'west',
	        split: true,
	        width: 320,
	        minSize: 250,
	        maxSize: 500,
	        rootVisible: false,
	        lines: true,
	        autoScroll: true,
	        
            animCollapse:false,
	        animate: false,
	        collapseMode:'mini',
	        loader: new Ext.tree.TreeLoader({
	    		dataUrl: 'functions/module_list.do',
	    		requestMethod: 'GET'
	    	}),
	    	//根节点
	    	root: new Ext.tree.AsyncTreeNode({id: 'root', text: '所有模块',  expanded:true}),
	    	tbar: new Ext.ux.StatusBar({
	    		defaultText: '模块',
				statusAlign: 'left',
				items: [
					{iconCls:'icon-folder-add', text:'新增', handler: this.addModule, scope: this},
					{iconCls:'icon-folder-edit', text:'编辑', handler: this.editModule, scope: this},
					{iconCls:'icon-folder-delete', text:'删除', handler: this.deleteModule, scope: this}
				]
			})
		});
		
		this.getSelectionModel().on('selectionchange', this.onSelectionChange, this)
   
    	this.loader.on('load', this.onLoad, this);
    
	    //显示右键菜单
	    this.on('contextmenu', this.onContextMenu, this);
	},
	
	onContextMenu: function(node, e) {
        if(!this.menu) {
            this.menu = new Ext.menu.Menu({
                id:'feeds-ctx',
                items: [
					{
			     		text:'修改模块',
			     		scope: this,
				   	 	handler:function(){  
			   				var editModuleDlg = new Ext.master.functions.ModuleWindow({moduleId: this.ctxNode.id, moduleNode: this.ctxNode});
			   				editModuleDlg.show();
			   				editModuleDlg.loadData();
			         	}
			        }, {
			     		text:'删除模块',
			     		scope: this,
				   	 	handler:function(){  
			        		deleteModule(this.ctxNode.id, this.ctxNode);
			         	}
			        }
				]
            });
            this.menu.on('hide', this.onContextHide, this);
        }
        
        if(this.ctxNode){
            this.ctxNode = null;
        }
        this.ctxNode = node;
        this.menu.showAt(e.getXY());
    },

    onContextHide : function(){
        if(this.ctxNode){
            this.ctxNode = null;
        }
    },

    afterRender : function(){
    	Ext.master.functions.ModuleTreePanel.superclass.afterRender.call(this);
        this.el.on('contextmenu', function(e){
            e.preventDefault();
        });
    },
    
    onSelectionChange: function(sm, node) {
    	if(node) {
    		this.funcListPanel.loadFunctionList(node.id, node.text);
    		
			Ext.Ajax.request({
				url: 'functions/get_module_description.do',
				params: {id: node.id},
				scope: this,
				success: function(response, options) {
					var responseText = Ext.util.JSON.decode(response.responseText);
		    		this.functionPanel.moduleDescript.update(
		    			'<div align="left" style="line-height:50px;font-size:12px;font-family:仿宋">' +
						responseText.description + '</div>');
				}
			});
    		
    	}
    },
    
    onLoad: function(loader, node, response) {
    	var childNode = node.firstChild;
    	if(childNode) {
    		childNode.select();
    	}
    },
    
    addModule: function() {
    	var moduleDlg = new Ext.master.functions.ModuleWindow();
		moduleDlg.show();
    },
    
    editModule: function() {
		var selectedNode = this.getSelectionModel().getSelectedNode();
		var moduleDlg = new Ext.master.functions.ModuleWindow();
		moduleDlg.show();
		moduleDlg.loadData(selectedNode.id);
    },
    
    deleteModule: function() {
		var selectedNode = this.getSelectionModel().getSelectedNode();
		var selectedId = selectedNode.id;
    	Ext.MessageBox.confirm('系统提示：','删除操作无法恢复，确认要删除当前功能吗？', function(btn){
			if(btn == 'yes') {
				Ext.Ajax.request({
					url: 'functions/delete_module.do',
					params: {id: selectedId},
					success: function(response, options) {
						var responseText = Ext.util.JSON.decode(response.responseText);
						if(responseText.success) {
							Ext.MessageBox.alert('系统提示：', responseText.value);
							selectedNode.remove();
						}else {
							Ext.MessageBox.alert('系统提示：', responseText.errorMsg);  
						}
					},
					failure: function(form, action){  
		                Ext.MessageBox.show({
		                    title: '提示信息',
		                    msg: "功能删除失败",
		                    buttons: Ext.MessageBox.OK,
		                    icon: Ext.MessageBox.ERROR
		                });
		            }
				});
			}
		});
    }
    
});

/**
 * 模块视窗
 * @class Ext.master.functions.ModuleWindow
 * @extends Ext.Window
 */
Ext.master.functions.ModuleWindow = Ext.extend(Ext.Window, { 
	parentId: '',
	parentName: '',
	moduleForm: null,
	
	constructor: function(_config) {
    	if (_config == null) {
			_config = {};
		}
		
		Ext.apply(this, _config);
		
		this.moduleForm = new Ext.master.functions.ModuleInfoForm();
		    
		Ext.master.functions.ModuleWindow.superclass.constructor.call(this, {
		    title: '模块',
		    border: false,
			width: 550,
			frame: true,
			closable: true,
			maximizable: false,
			minimizable: false,
			autoDestroy: true,
			closeAction: 'close',
			modal: true,
			buttonAlign: 'center',
			bodyStyle: 'padding-top: 2px'
		});
	},
	
    initComponent: function() {
    	
		this.items = [ 
			this.moduleForm
		];
		
    	this.buttons = [
    		{	
				text: '提交',
				scope: this,
				handler: function(){
					var form = this.moduleForm.getForm();
					if(form.isValid()) {
						Ext.MessageBox.wait('正在处理，请稍等... ');  
						form.submit(
							{
								clientValidation: true,
	    						url: 'functions/save_module.do',
	    						waitTitle: '系统提示：',
	    						waitMsg: '正在保存数据，请稍等......',
	    						scope: this,
							    success: function(form, action) {
									if(action.result.success) {
										Ext.MessageBox.alert('系统提示：', action.result.value);

										if(action.result.isnew) {
											
		    						    	var childNode = new Ext.tree.TreeNode({
		    						    		id: action.result.id, 
		    						    		text: action.result.name,
		    						    		icon: action.result.icon
		    						    	});
									    	var parentPKField = form.findField("parentId");
									    	var parentPk = parentPKField.getValue();
									    	var moduleTree = Ext.getCmp("moduleTree");
									    	if(parentPk == null || parentPk == "") {
									    		moduleTree.getRootNode().appendChild(childNode);
									    	} else {
									    		var parentNode = moduleTree.getNodeById(parentPk);
									    		parentNode.appendChild(childNode);	
									    	}
									    	
										}else {
											var moduleTree = Ext.getCmp("moduleTree");
											var selectedNode = moduleTree.getSelectionModel().getSelectedNode();
									 		selectedNode.setText(action.result.name);
									 		
									 		var moduleDescript = Ext.getCmp("moduleDescript")
									 		if(moduleDescript)
									 			moduleDescript.update('<div align="left" style="line-height:50px;font-size:12px;font-family:仿宋">' +
													action.result.description + '</div>');
										}
										
								    	this.close();
									}else {
										Ext.MessageBox.alert('系统提示：', action.result.errorMsg);  
									}
							    },
							    failure: function(form, action) {  
					                Ext.MessageBox.show({
					                    title: '提示信息',
					                    msg: "保存失败",
					                    buttons: Ext.MessageBox.OK,
					                    icon: Ext.MessageBox.ERROR
					                });
					            }
							}
						);
					} 
				}
			}, {
                text: '关闭',
                scope: this,
                handler: function(){
                	this.close();
                }
			}
    	];
    	Ext.master.functions.ModuleWindow.superclass.initComponent.call(this);
    },
    
    initData: function() {
    	var record = new Ext.data.Record({
    		parentId: this.parentId,
    		parentName: this.parentName,
    		id: '0'
    	});
    	this.moduleForm.getForm().loadRecord(record);
    },
    
    loadData: function(id) {
    	var store = new Ext.data.JsonStore({
    		url: 'functions/get_module.do',
    		root: 'resultSet', 
    		fields: [
    			'id', 
    			'name', 
    			'url',
    			'parentId',
    			'description',
    			'icon'
    		]    		
		});
		
    	store.load({
    		params: {id: id},
    		callback: function(records, options, success) {
    			if(success && records.length == 1) {
    				this.moduleForm.getForm().loadRecord(records[0]);
			    	this.moduleForm.getForm().findField("parentId").setDisabled(true);
    			}
    		},
    		scope: this
    	});
    	
    }
});

/**
 * 模块表单
 * @class Ext.master.functions.ModuleInfoForm
 * @extends Ext.form.FormPanel
 */
Ext.master.functions.ModuleInfoForm = Ext.extend(Ext.form.FormPanel, {
    frame: true,
    border: false,
    bodyStyle: 'padding-top: 2px',
    labelWidth: 100,
    defaults: {
		msgTarget: 'under',
		anchor: '100%'
	},
	
	constructor: function(_config) {
    	if (_config == null) {
			_config = {};
		}
		Ext.apply(this, _config);
		
    	this.items = [
    			{
					xtype: "treefield",
					fieldLabel: '上级模块',
					id: 'parentId',
					hiddenName: 'parentId',
					dataUrl: 'functions/module_list.do',
					listHeight: 200,
					listeners: {
						'select': {
				        	fn: function(field, selectNode) {
				        		var orgtype = selectNode.attributes.orgtype;
							},
				        	scope: this
				        }
					}
				},
				new HelpTip({
					leftWidth:100,
					tipValue: 'A.如果不选择上级模块，当前添加的模块为一级模块。<br/>' +
							'B.如果选择上级模块，当前添加的模块为选中模块的子模块。',
					displayValue: '选择上级模块需注意'
				}),
				{
					xtype: "textfield",
					fieldLabel: '模块名称<font style="color:red">*</font>',
					name: 'name', 
					allowBlank: false, 
					blankText: "模块名称不能为空."
				}, {
					xtype: "textarea",
					fieldLabel: '模块描述', 
					name: 'description', 
					height: 100
				}, {	
					xtype: "textfield",
					fieldLabel: '模块URL<font style="color:red">*</font>',
					name: 'url', 
					allowBlank: false, 
					blankText: "模块URL不能为空."
				}, {
					xtype: 'hidden',
					name: 'id'
				}, {
					xtype: 'hidden',
					name: 'ver'
				}
    	];
    	Ext.master.functions.ModuleInfoForm.superclass.constructor.call(this);
    }
});


/**
 * 功能面板
 * @class Ext.master.functions.FunctionPanel
 * @extends Ext.Panel
 */
Ext.master.functions.FunctionPanel = Ext.extend(Ext.Panel, {
	id: 'functionPanel',
	region: 'center',
	layout: 'border',
	moduleDescript: null,
	funcListPanel: null,

	constructor: function(_config) {
		if (_config == null) {
			_config = {};
		}
		Ext.apply(this, _config);
		 
		this.tbar = new Ext.ux.StatusBar({
    		defaultText: '模块描述',
			statusAlign: 'left'
		});
			
		this.items = [
  	        this.moduleDescript,
  	        this.funcListPanel
        ];
		Ext.master.functions.FunctionPanel.superclass.constructor.call(this);
    }
});

/**
 * 模块描述信息
 * @class Ext.master.functions.ModuleDescript
 * @extends Ext.Panel
 */
Ext.master.functions.ModuleDescript = Ext.extend(Ext.Panel, {
	id: 'moduleDescript',
	region: 'north',
	frame: true,
	border: false,
	autoHeight: true,
    initComponent: function() {
		this.html = '<div align="left" style="line-height:50px;font-size:12px;font-family:仿宋">' +
			'这个区域是模块的描述信息</div>';
        Ext.master.functions.ModuleDescript.superclass.initComponent.call(this);
    }
});

/**
 * 功能列表
 * @class Ext.master.functions.FunctionListGridPanel
 * @extends Ext.grid.GridPanel
 */
Ext.master.functions.FunctionListGridPanel = Ext.extend(Ext.grid.GridPanel, {
	id: 'functionListGrid',
	enableHdMenu: false,
	stripeRows: false,
	disableSelection: true,
	trackMouseOver: false,
    autoExpandColumn: 'description',
	loadMask: {msg:'正在读取功能列表......'},
	region: 'center',
    sm: new Ext.grid.RowSelectionModel({
        singleSelect:true
    }),
    
    moduleId: '',
    moduleName: '',
    
    initComponent: function() {
    	
    	this.actionRender = function(val, metadata, record, rowIndex, colIndex, store) {
    		var moduleId = record.get("moduleId");
    		return '<a style="font-size:12px" href="javascript:Ext.master.functions.editFunction(\''+ val +'\')">【修改】</a>' +
					'<a style="font-size:12px" href="javascript:Ext.master.functions.deleteFunction(\''+ val +'\',\''+ moduleId +'\')">【删除】</a>';
    	};
    	
    	this.store = new Ext.data.JsonStore({
    		url: 'functions/function_list.do', 
    		root: 'resultSet',
			totalProperty: 'totalCount',
			idProperty: 'functionId', 
			fields: [ 
				'functionId',
				'moduleId',
				'name', 
				'description'
			],
    		autoLoad: false
    	});
    	
        this.columns = [
           {id: 'name', header: "功能名称", dataIndex: 'name', sortable: false, width: 150},
           {id: 'description', header: "功能描述", dataIndex: 'description', sortable: false},
           {id: 'action', header: '操作', dataIndex: 'functionId', sortable: false, width: 120, align: 'center', renderer: this.actionRender}
    	];
    	
    	this.tbar = new Ext.ux.StatusBar({
			statusAlign: 'left',
			items: ['->', {iconCls:'icon-add', text: '功能', handler: this.addFunction, scope: this}]
		});
    	
        Ext.master.functions.FunctionListGridPanel.superclass.initComponent.call(this);
    },
    
    loadFunctionList: function(moduleId, moduleName) {
    	this.moduleId = moduleId;
    	this.moduleName = moduleName;
    	
    	var title = moduleName + "功能列表";
    	this.getTopToolbar().setText(title);
    	this.store.load({params: {moduleId: moduleId}});
    },
    
    reloadFunctionList: function() {
    	this.store.load({params: {moduleId: this.moduleId}});
    },
    
    addFunction: function() {
		var dlg = new Ext.master.functions.FunctionWindow({moduleId: this.moduleId, moduleName: this.moduleName});
    	dlg.show();
    	dlg.initData();
    }

});

/**
 * 编辑功能
 * @param {} id
 */
Ext.master.functions.editFunction = function(id) {
	var dlg = new Ext.master.functions.FunctionWindow(id);
	dlg.show();
	dlg.loadData(id);
};

/**
 * 删除功能
 * @param {} id
 */
Ext.master.functions.deleteFunction = function(id, moduleId) {
	Ext.MessageBox.confirm('系统提示：','删除操作无法恢复，确认要删除当前功能吗？', function(btn){
		if(btn == 'yes') {
			Ext.Ajax.request({
				url: 'functions/delete_function.do',
				params: {id: id},
				success: function(response, options) {
					var responseText = Ext.util.JSON.decode(response.responseText);
					if(responseText.success) {
						Ext.MessageBox.alert('系统提示：', responseText.value);
						Ext.getCmp("functionListGrid").store.load({params: {moduleId: moduleId}});
					}else {
						Ext.MessageBox.alert('系统提示：', responseText.errorMsg);  
					}
				},
				failure: function(form, action){  
	                Ext.MessageBox.show({
	                    title: '提示信息',
	                    msg: "功能删除失败",
	                    buttons: Ext.MessageBox.OK,
	                    icon: Ext.MessageBox.ERROR
	                });
	            }
			});
		}
	});
};

/**
 * 功能窗口
 * @class Ext.master.functions.FunctionWindow
 * @extends Ext.Window
 */
Ext.master.functions.FunctionWindow = Ext.extend(Ext.Window, { 
	moduleId: '',
	moduleName: '',
	functionForm: null,
	
	constructor: function(_config) {
    	if (_config == null) {
			_config = {};
		}
		
		Ext.apply(this, _config);
		
		this.functionForm = new Ext.master.functions.FunctionInfoForm();
		    
		Ext.master.functions.FunctionWindow.superclass.constructor.call(this, {
		    title: '功能',
		    border: false,
			width: 650,
			frame: true,
			closable: true,
			maximizable: false,
			minimizable: false,
			autoDestroy: true,
			closeAction: 'close',
			modal: true,
			buttonAlign: 'center',
			bodyStyle: 'padding-top: 2px'
		});
	},
	
    initComponent: function() {
    	
		this.items = [ 
			this.functionForm
		];
		
    	this.buttons = [
    		{	
				text: '提交',
				scope: this,
				handler: function(){
					var form = this.functionForm.getForm();
					if(form.isValid()) {
						Ext.MessageBox.wait('正在处理，请稍等... ');  
						form.submit(
							{
								clientValidation: true,
	    						url: 'functions/save_function.do',
	    						waitTitle: '系统提示：',
	    						waitMsg: '正在保存数据，请稍等......',
	    						scope: this,
							    success: function(form, action) {
									if(action.result.success) {
										Ext.MessageBox.alert('系统提示：', action.result.value);
								    	if(Ext.getCmp("functionListGrid")) {
								    		Ext.getCmp("functionListGrid").reloadFunctionList();
								    	}
								    	this.close();
									}else {
										Ext.MessageBox.alert('系统提示：', action.result.errorMsg);  
									}
									
							    },
							    failure: function(form, action) {  
					                Ext.MessageBox.show({
					                    title: '提示信息',
					                    msg: "保存失败",
					                    buttons: Ext.MessageBox.OK,
					                    icon: Ext.MessageBox.ERROR
					                });
					            }
							}
						);
					} 
				}
			}, {
                text: '关闭',
                scope: this,
                handler: function(){
                	this.close();
                }
			}
    	];
    	Ext.master.functions.FunctionWindow.superclass.initComponent.call(this);
    },
    
    initData: function() {
    	var record = new Ext.data.Record({
    		moduleId: this.moduleId,
    		moduleName: this.moduleName,
    		id: '0'
    	});
    	this.functionForm.getForm().loadRecord(record);
    },
    
    loadData: function(id) {
    	var functionStore = new Ext.data.JsonStore({
    		url: 'functions/get_function.do',
    		root: 'resultSet', 
    		fields: [
    			'id', 
    			'name', 
    			'url',
    			'moduleId',
    			'description',
    			'icon'
    		]    		
		});
		
    	functionStore.load({
    		params: {id: id},
    		callback: function(records, options, success) {
    			if(success && records.length == 1) {
    				this.functionForm.getForm().loadRecord(records[0]);
    			}
    		},
    		scope: this
    	});
    }
});

/**
 * 功能表单
 * @class Ext.master.functions.FunctionInfoForm
 * @extends Ext.form.FormPanel
 */
Ext.master.functions.FunctionInfoForm = Ext.extend(Ext.form.FormPanel, {
    frame: true,
    border: false,
    bodyStyle: 'padding-top: 2px',
    labelWidth: 100,
    defaults: {
		msgTarget: 'under',
		anchor: '100%'
	},
	
	constructor: function(_config) {
    	if (_config == null) {
			_config = {};
		}
		Ext.apply(this, _config);
		
    	this.items = [
				{	
					xtype: "textfield",
					fieldLabel: '功能名称<font style="color:red">*</font>',
					name: 'name', 
					allowBlank: false, 
					blankText: "功能名称不能为空."
				}, {
					xtype: "htmleditor",
					fieldLabel: '功能描述', 
					name: 'description', 
					height: 100
				}, {	
					xtype: "textfield",
					fieldLabel: '功能URL<font style="color:red">*</font>',
					name: 'url', 
					allowBlank: false, 
					blankText: "功能URL不能为空."
				}, {
					xtype: 'hidden',
					name: 'moduleId'
				}, {
					xtype: 'hidden',
					name: 'id'
				}, {
					xtype: 'hidden',
					name: 'ver'
				}
    	];
    	Ext.master.functions.FunctionInfoForm.superclass.constructor.call(this);
    }
});
